package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @author 霍森彪
 * @date 2022/7/28 11:55
 */
@Slf4j
@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 点赞与取消点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //获取userId
        Integer userId = user.getId();
        if (userId == null || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 组装Kafka消息
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
        //点赞逻辑
        if (dto.getOperation() == 0){
            //首先去重
            Object likeExist = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId(), userId.toString());
            if (likeExist != null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"点赞记录已存在");
            }
            //添加点赞记录
            Long currentTimeMillis = System.currentTimeMillis();
            cacheService.hPut(BehaviorConstants.LIKE_BEHAVIOR+dto.getArticleId(),userId.toString(),currentTimeMillis.toString());
            //判断是新增消息还是减少
            mess.setAdd(1);
        }else {
            //取消点赞逻辑
            cacheService.hDelete(BehaviorConstants.LIKE_BEHAVIOR+dto.getArticleId(),userId.toString());
            mess.setAdd(-1);
        }
        //发送消息，数据聚合
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
